package com.gyc.simple.sysuser.config.shiro;

import com.gyc.simple.common.util.DateUtils;
import com.gyc.simple.common.util.JwtUtils;
import com.gyc.simple.common.util.MD5Utils;
import com.gyc.simple.common.util.RedisUtils;
import com.gyc.simple.common.vo.User;
import com.gyc.simple.sysuser.entity.base.IUser;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class MyCredentialsMatcher implements CredentialsMatcher {


    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        SimpleAuthenticationInfo simpleAuthenticationInfo = (SimpleAuthenticationInfo) info;
        IUser getTime = (IUser) simpleAuthenticationInfo.getPrincipals().getPrimaryPrincipal();
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String pawdInfo =String.valueOf(usernamePasswordToken.getPassword())+DateUtils.dateToString(getTime.getIuRegistertime(),"yyyy/MM/dd HH:mm:ss");
        String pwd = MD5Utils.getMD5String(pawdInfo);
        //如果登录成功 生成jwt,以 jwt_登录名 存入Redis过期时间3分钟
        if(pwd.equals(info.getCredentials())){
            String jwt = JwtUtils.createTokenWithClaim(new User(getTime.getIuId(),getTime.getIuLname()));
            //存储jwt在登录控制器取出返回给用户
            RedisUtils.set("jwt_"+getTime.getIuLname(),jwt);
            RedisUtils.expire("jwt_"+getTime.getIuLname(),3, TimeUnit.MINUTES);

        }
        return pwd.equals(info.getCredentials());
    }


}
